package com.yuanda.erp9.syn.service.erp9.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.innovation.ic.b1b.framework.util.StringUtils;
import com.yuanda.erp9.syn.contant.RateCalculateConstants;
import com.yuanda.erp9.syn.entity.CmsBrandsTempEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsEntity;
import com.yuanda.erp9.syn.entity.CmsGoodsInformationEntity;
import com.yuanda.erp9.syn.entity.CmsPricesEntity;
import com.yuanda.erp9.syn.enums.CachePrefixEnum;
import com.yuanda.erp9.syn.enums.DeliveryAreaEnum;
import com.yuanda.erp9.syn.enums.SourceEnum;
import com.yuanda.erp9.syn.enums.SubjectSupplierEnum;
import com.yuanda.erp9.syn.exception.TargetServerException;
import com.yuanda.erp9.syn.execule.thread.Master;
import com.yuanda.erp9.syn.helper.RetryOperateLogHelper;
import com.yuanda.erp9.syn.helper.VanlinkonHelper;
import com.yuanda.erp9.syn.pojo.CmsGoodsPojo;
import com.yuanda.erp9.syn.service.erp9.CmsTopicUpdateSumLogService;
import com.yuanda.erp9.syn.service.erp9.VanlinkonService;
import com.yuanda.erp9.syn.util.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;


/**
 * @ClassName VanlinkonExcelServiceImpl
 * @Description
 * @Date 2022/12/15
 * @Author myq
 */
@Service
@Slf4j
public class VanlinkonServiceImpl implements VanlinkonService {

    @Autowired
    private VanlinkonHelper vanlinkonHelper;

    @Autowired
    private RetryOperateLogHelper retryOperateLogHelper;

    @Autowired
    private CmsTopicUpdateSumLogService cmsTopicUpdateSumLogService;

    private final String SUPPLIER = "Vanlinkon";
    private final String US_CODE = "US000008805";

    /**
     * @Description: 解析文件并发送至队列
     * @Params:
     * @Return:
     * @Author: Mr.myq
     * @Date: 2022/12/159:41
     */
    @Override
    public void parse(Long pk) {
        AtomicInteger sum = new AtomicInteger(0);
        CacheUtil.Cache brandCache = CacheUtil.init(CachePrefixEnum.BRAND.getKey());
        CacheUtil.Cache supplierCache = CacheUtil.init(CachePrefixEnum.SUPPLIERS.getKey());
        Integer supplierId = supplierCache.get(SUPPLIER);
        int page = 1;
        Master<CmsGoodsPojo> objectMaster = new Master<>(supplierId, null, SourceEnum.DATA_PACKAGE.getCode());
        JSONArray jsonArray = null;
        try {
            while (true) {
                JSONObject jsonObject = vanlinkonHelper.getData(page++);
                jsonArray = JSONArray.parseArray(jsonObject.getString("data"));
                if (jsonArray.size() == 0) {
                    break;
                } else {
                    try {
                        for (int x = 0; x < jsonArray.size(); x++) {
                            sum.incrementAndGet();
                            JSONObject param = JSON.parseObject(jsonArray.getString(x));
                            // 包装类
                            CmsGoodsPojo cmsGoodsPojo = new CmsGoodsPojo();
                            //商品类
                            CmsGoodsEntity cmsGoodsEntity = new CmsGoodsEntity();
                            cmsGoodsEntity.setAdminid(0);
                            cmsGoodsEntity.setTenantsid(0);
                            cmsGoodsEntity.setClassifyid(0);
                            cmsGoodsEntity.setImg("");
                            cmsGoodsEntity.setType(0);
                            cmsGoodsEntity.setStatus(1);
                            cmsGoodsEntity.setStatusMsg("");
                            cmsGoodsEntity.setDataType(1);
                            cmsGoodsEntity.setModel(param.getString("product_no"));
                            CmsBrandsTempEntity cmsBrandsTempEntity = new CmsBrandsTempEntity();
                            cmsBrandsTempEntity.setTag(0);
                            String brand = param.getString("brand");
                            cmsBrandsTempEntity.setName(StringUtils.isNotEmpty(brand) ? brand : "unknown_brand");
                            Integer brandId = brandCache.insertAndGet(cmsBrandsTempEntity);
                            cmsGoodsEntity.setBrand(brandId);
                            cmsGoodsEntity.setBrandName(brand);
                            cmsGoodsEntity.setSupplier(supplierId);
                            cmsGoodsEntity.setSplName(SUPPLIER);
                            String incodes = EasyExcelUtils.getIncodes(param.getString("id"), US_CODE, supplierId);
                            cmsGoodsEntity.setIncodes(incodes);
                            cmsGoodsEntity.setGoodid(incodes);
                            cmsGoodsEntity.setIsSampleApply(0);
                            cmsGoodsEntity.setBatch("");
                            cmsGoodsEntity.setOriginalPrice(new BigDecimal("0.00"));
                            cmsGoodsEntity.setPurchasePrice(new BigDecimal("0.00"));
                            cmsGoodsEntity.setRepertory(StringUtils.isNotEmpty(param.getString("stock")) ? param.getInteger("stock") : 0);
                            String storeid = param.getString("storeid");
                            cmsGoodsEntity.setRepertoryArea(vanlinkonHelper.getStore(storeid));
                            cmsGoodsEntity.setPublish(1);
                            cmsGoodsEntity.setDescribe("");
                            cmsGoodsEntity.setFiles("");
                            cmsGoodsEntity.setPayType(0);
                            Integer restriction = param.getInteger("restriction");
                            cmsGoodsEntity.setDeliveryArea(DeliveryAreaEnum.DOMESTIC.getCode());
                            cmsGoodsEntity.setDomesticDate("5-7工作日");
                            cmsGoodsEntity.setHongkongDate("");
                            long mqp = param.getLong("is_mpq");
                            long max = Math.max(mqp, 1L);
                            cmsGoodsEntity.setIncremental(max);
                            cmsGoodsEntity.setSource(SourceEnum.DATA_PACKAGE.getCode());
                            cmsGoodsEntity.setMpq(max);
                            cmsGoodsEntity.setHisp(null);
                            cmsGoodsEntity.setSales(0);
                            cmsGoodsEntity.setClick(0);
                            cmsGoodsEntity.setVisitor(0);
                            cmsGoodsEntity.setCreatedAt(DateUtils.now());
                            cmsGoodsEntity.setUpdatedAt(DateUtils.now());
                            cmsGoodsEntity.setActivityId(0);
                            cmsGoodsEntity.setContent(null);
                            //费率
                            JSONObject data = RateCalculateUtil.getRate(cmsGoodsEntity.getBrandName(), cmsGoodsEntity.getModel());

                            // 费率信息
                            JSONObject rateJsonObject = (JSONObject) data.get(RateCalculateConstants.RATE);

                            cmsGoodsEntity.setRates(rateJsonObject);
                            //关税
                            BigDecimal tariffRate = rateJsonObject.getBigDecimal(RateCalculateConstants.TARIFFRATE_FIELD);
                            //商检税
                            BigDecimal cIQprice = rateJsonObject.getBigDecimal(RateCalculateConstants.CIQPRICE_FIELD);
                            //税费计算和存储
                            if (tariffRate != null) {
                                cmsGoodsEntity.setTariffsRate(tariffRate.doubleValue());
                            }
                            if (cIQprice != null) {
                                cmsGoodsEntity.setInspectionChargesFee(cIQprice.doubleValue());
                            }
                            cmsGoodsEntity.setEmbargo(data.get(RateCalculateConstants.EMBARGO_FIELD) == null ? 0 : data.getInteger(RateCalculateConstants.EMBARGO_FIELD));
                            cmsGoodsEntity.setCcc(data.get(RateCalculateConstants.CCC_FIELD) == null ? 0 : data.getInteger(RateCalculateConstants.CCC_FIELD));
                            cmsGoodsEntity.setEccnNo(data.getString(RateCalculateConstants.ECCN_FIELD));

                            // 参数
                            cmsGoodsEntity.setParams(null);
                            // 阶梯价格
                            Integer isLadder = param.getInteger("is_ladder");
                            List<Map<String, String>> ladderPrice = vanlinkonHelper.getLadderPrice(isLadder, param.getBigDecimal("price"), param.getInteger("is_vip_discount"), storeid, JSON.parseArray(param.getString("ladder_info")));
                            cmsGoodsEntity.setPrices(JSON.toJSONString(ladderPrice));
                            if (Integer.valueOf(1).equals(isLadder)) {
                                if (!CollectionUtils.isEmpty(ladderPrice)) {
                                    int count = (int) Math.ceil(50 / Double.parseDouble(ladderPrice.get(0).get("price")));
                                    cmsGoodsEntity.setMinimumOrder((long) Math.max((count == 0 ? 1 : count), restriction));
//                                    cmsGoodsEntity.setUnitPrice(Double.parseDouble(MathUtil.divide(ladderPrice.get(0).get("price"), cmsGoodsEntity.getMinimumOrder(), 4)));
                                } else {
                                    cmsGoodsEntity.setMinimumOrder((long) Math.max(restriction, 1));
//                                    cmsGoodsEntity.setUnitPrice(0.0000);
                                }
                            } else {
                                cmsGoodsEntity.setMinimumOrder(1L);
                            }
                            cmsGoodsPojo.setCmsGoodsEntity(cmsGoodsEntity);

                            CmsGoodsInformationEntity cmsGoodsInformationEntity = new CmsGoodsInformationEntity();
                            cmsGoodsInformationEntity.setEcnn(1);
                            cmsGoodsInformationEntity.setAtlas("");
                            cmsGoodsInformationEntity.setContent(null);
                            cmsGoodsInformationEntity.setActivity(0);
                            cmsGoodsInformationEntity.setEcnnnumber("");
                            cmsGoodsInformationEntity.setTariffs(0);
                            cmsGoodsInformationEntity.setGoodid(incodes);
                            cmsGoodsInformationEntity.setTariffsrate(0);
                            cmsGoodsInformationEntity.setInspectionCharges(0);
                            cmsGoodsInformationEntity.setInspectionChargesFee(cmsGoodsEntity.getInspectionChargesFee());
                            cmsGoodsInformationEntity.setParams(null);
                            cmsGoodsInformationEntity.setCreatedAt(new Date());
                            cmsGoodsPojo.setCmsGoodsInformationEntity(cmsGoodsInformationEntity);

                            // price
                            List<CmsPricesEntity> pricesEntities = new ArrayList<>(6);
                            for (Map<String, String> m : ladderPrice) {
                                CmsPricesEntity pricesEntity = new CmsPricesEntity();
                                pricesEntity.setLadderid(0);
                                pricesEntity.setGoodid(incodes);
                                pricesEntity.setMin(Long.parseLong(m.get("min")));
                                pricesEntity.setMax(Long.parseLong(m.get("max")));
                                pricesEntity.setPrice(BigDecimal.valueOf(Double.parseDouble(m.get("price"))));
                                pricesEntity.setCurrency(Integer.parseInt(m.get("currency")));
                                pricesEntity.setPosition(Integer.parseInt(m.get("position")));
                                pricesEntity.setDiscountRate(new BigDecimal(m.get("discount_rate")));
                                pricesEntity.setDiscountPrice(new BigDecimal(m.get("discount_price")));
                                pricesEntity.setPublish(0);
                                pricesEntity.setCreatedAt(new Date());
                                pricesEntity.setUpdatedAt(new Date());
                                pricesEntities.add(pricesEntity);
                            }
                            cmsGoodsPojo.setCmsPricesEntityList(pricesEntities);
                            objectMaster.add(cmsGoodsPojo);
                        }
                    } catch (TargetServerException e) {
                        log.warn("Vanlinkon解析错误：无法连接到目标服务器");
                        throw new TargetServerException(e.getMessage(), supplierId, SubjectSupplierEnum.VANLINKON.getSubject());
                    } catch (Exception e1) {
                        log.warn("Vanlinkon解析错误,丢弃测数据。");
                        retryOperateLogHelper.add(jsonArray, supplierId, e1.toString(), false);
                    }
                }
            }
        } finally {
            // 退出标志
            objectMaster.isBegin = false;
            cmsTopicUpdateSumLogService.insertBySum(sum.longValue(), pk);
        }


    }


}
